jest での mock について
jest での mock について
mock はむずい
ドキュメント読んでも、「このパターンはどうするの?」的なケースが多い気がする
Jest will automatically hoist jest.mock calls to the top of the module (before any imports).
つまり、テストファイルで jest.mock したものは、実装ファイルでの import より優先されるということかな?
import がキャッシュされるから、みたいな話があるらしい
となると、DI で mock object を差し込むとかする必要がないように思えるのだがどうだろうか?
このスクラップで紹介されていたが、この stack overflow は助かった
あるファイルから複数の関数が named export されている場合、どのように mock する?
jest.mock(モジュール) ができない?
一言で言えばこういう感じにすればよい
code:exmaple.test.js
import * as named from ./hoge
(named as unkown as jest.Mock).mockRetureValue()
詳細
jest.SpyOn はテストないで直接実行される関数でなくても spy してくれる?
結論、してくれる
mock fetch
専用のライブラリがいくつかあるようだが、あまりメンテされていないようなので自分でやるのがよさそう
code:example.test.ts
global.fetch = jest.fn();
it('got correct response', () => {
expect.assertions(1);
fetch.mockResolvedValueOnce(successResp);
return callFetchInside().then(resp => {
expect(resp).toBe(something);
});
}
Test file で直接 import していないモジュールも mock できる
参考
code:A.ts
import { funcB } from 'B'
export funcA = (arg) => funcB(arg)
code:B.ts
export funcB = () => {}
code:A.test.ts
jest.mock('B', () => {
const originalModule = jest.requireActual('B');
return {
__esModule: true,
...originalModule,
funcB: jest.fn(),
};
})
test('test', () => {
jest.requireMock('B').B.mockReturnValue('mocked return');
// write test
}